package com.org.flow.system.service.impl;

import com.org.flow.core.exception.FlowBusException;
import com.org.flow.system.mapper.BusinessExceptionLogMapper;
import com.org.flow.system.model.bo.order.GovernmentBO;
import com.org.flow.system.model.dos.log.BusinessExceptionLogDTO;
import com.org.flow.system.service.LogService;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Date;

@Service
@RequiredArgsConstructor
@Slf4j
public class LogServiceImpl implements LogService {

    /*异常记录*/
    private final BusinessExceptionLogMapper businessExceptionLogMapper;
    /*事务上下文*/
    private final PlatformTransactionManager txManager;

    @Override
    public void insErrorLog(NodeComponent cmp, Exception e) {
        // 手动开启事务  start
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = txManager.getTransaction(def);
        // 手动开启事务  end
        BusinessExceptionLogDTO dto = new BusinessExceptionLogDTO();

        GovernmentBO bo =  cmp.getRequestData();
        dto.setBusinessId(bo.getId());
        dto.setExceptionType(e.getClass().getName());
        dto.setExceptionMsg(e.getMessage());
        if (e instanceof FlowBusException){
            dto.setExceptionCode(((FlowBusException) e).getCode());
        }else{
            dto.setExceptionCode("500");
        }
        dto.setUpdateTime(new Date());
        businessExceptionLogMapper.insertSelective(dto);
        txManager.commit(status);
    }

    @Override
    public void insErrorLog(BusinessExceptionLogDTO dto, Exception e) {
        // 手动开启事务  start
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = txManager.getTransaction(def);
        // 手动开启事务  end
        if (e instanceof FlowBusException){
            dto.setExceptionCode(((FlowBusException) e).getCode());
        }else{
            dto.setExceptionCode("500");
        }
        dto.setExceptionType(e.getClass().getName());
        dto.setExceptionMsg(e.getMessage());
        dto.setUpdateTime(new Date());
        businessExceptionLogMapper.insertSelective(dto);
        txManager.commit(status);
    }





}
